package com.ccp.dev.qbdms.webservice.cxf;

import com.alibaba.fastjson.JSONObject;
import com.ccp.dev.core.basic.base.BaseService;
import com.ccp.dev.core.basic.response.ResultData;
import com.ccp.dev.core.util.AppUtil;
import com.ccp.dev.core.util.BeanUtils;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.qbdms.webservice.CommonWebService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.springframework.context.annotation.Bean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * cxf 客户端
 * @author y
 */
public class CxfClient {
    private static final Log logger = LogFactory.getLog(CxfClient.class);

    public static final String SERVICE = "Service";

    /**
     * 发送消息公共类
     * @param serviceName  serviceName
     * @param methodName   methodName
     * @param map 参数
     * @param code 组织code
     * @return ResultData
     */
    public static ResultData sendMsg(String serviceName, String methodName, Map<String,Object> map , String code){
        if(StringUtil.isEmpty(serviceName)){
            logger.debug("param serviceName cannot be null。");
            throw new IllegalArgumentException("param serviceName cannot be null。");
        }
        if(StringUtil.isEmpty(methodName)){
            logger.debug("param methodName cannot be null。");
            throw new IllegalArgumentException("param methodName cannot be null。");
        }
        if(null == map){
            map = new HashMap<>(2);
        }
        map.put("web_serviceName",getClassName(serviceName));
        map.put("web_methodName",methodName);
        try {
            CommonWebService commonWebService = getInterface(code);
            return JSONObject.parseObject(commonWebService.invoke(JSONObject.toJSONString(map)),ResultData.class);
        }catch (Exception e){
            logger.debug("param methodName cannot be null。");
            return ResultData.error("Interface call failed。");
        }
    }

    /**
     * 获取接口
     * @param code 组织code  用于获取不同系统的ip地址
     * @return CommonWebService接口
     */
    public static CommonWebService getInterface(String code) {
        // 接口地址
        String address = getAddress(code);
        // 代理工厂
        JaxWsProxyFactoryBean jaxWsProxyFactoryBean = new JaxWsProxyFactoryBean();
        // 设置代理地址
        jaxWsProxyFactoryBean.setAddress(address);
        // 设置接口类型
        jaxWsProxyFactoryBean.setServiceClass(CommonWebService.class);
        // 创建一个代理接口实现
        return (CommonWebService) jaxWsProxyFactoryBean.create();
    }

    /**
     * 根据code获取连接地址
     * @param code 组织code
     * @return 连接地址
     */
    private static String getAddress(String code){
        if(StringUtil.isEmpty(code)){
            logger.debug("param code cannot be null。");
            throw new IllegalArgumentException("param code cannot be null。");
        }
        Map map = getMappingMap();
        return null == map.get(code) ? null : String.valueOf(map.get(code)) ;
    }

    /**
     * 映射map  组织code和webService接口的映射
     * @return map
     */
    @Bean
    public static Map<String,String> getMappingMap(){
        Map<String,String> map = new HashMap<>();
        map.put("kaifa","http://192.168.0.56:8080/services/CommonWebService?wsdl");//集团
        map.put("kfzz2","http://192.168.0.56:8090/services/CommonWebService?wsdl");//院
        map.put("kfzz3","http://192.168.0.56:8100/services/CommonWebService?wsdl");//所
        return map;
    }

    /**
     *
     * @param modelName 应该拿到首字母小写的name
     * @param ids 数据集ids
     * @return list
     */
    public static List<Object> getDataSet(String modelName , String ids){
        modelName = getClassName(modelName);
        Object obj = AppUtil.getBean(modelName+SERVICE);
        if(BeanUtils.isEmpty(obj)){
            logger.debug("bean "+modelName+"Service is not defined。" );
            throw new IllegalArgumentException("bean "+modelName+"Service is not defined。" );
        }
        if(StringUtil.isEmpty(ids)){
            logger.debug("param ids cannot be null。");
            throw new IllegalArgumentException("param ids cannot be null。" );
        }
        BaseService baseService = (BaseService)obj;
        String[] businessIds = ids.split(",");
        List<Object> list = new ArrayList<>();
        for(String businessId : businessIds){
            list.add(baseService.getOneById(businessId));
        }
        return list;
    }

    /**
     * 根据类名判断首字母是否需要小写
     * @param className 类名称
     * @return string
     */
    public static String getClassName(String className){
        if(className.length()>1){
            char charName  = className.charAt(1);
            if(Character.isUpperCase(charName)){
                className = StringUtil.makeFirstLetterUpperCase(className);
            }else{
                className = StringUtil.convertToCamelFirstLowerCase(className);
            }
        }
        return className;
    }
}
